package cn.harry.cabinet.view.fragments

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.app.TimePickerDialog
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.widget.SwitchCompat
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import cn.harry.cabinet.R
import cn.harry.cabinet.database.AppDatabase
import cn.harry.cabinet.utils.logConfigChange
import cn.harry.cabinet.viewmodel.ProgramManagementViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import kotlin.system.exitProcess

class ProgramManagementFragment : BaseFragment() {

    companion object {
        private const val TAG = "ProgramManagementFragment"
    }
    private val viewModel: ProgramManagementViewModel by viewModels()
    
    // UI组件 - 数据管理
    private lateinit var clearDataButton: Button
    private lateinit var restartAppButton: Button
    private lateinit var exitAppButton: Button
    
    // UI组件 - 系统监控
    private lateinit var monitorStatusText: TextView
    private lateinit var startMonitorButton: Button
    private lateinit var stopMonitorButton: Button
    private lateinit var memoryInfoText: TextView
    private lateinit var cpuInfoText: TextView
    private lateinit var processInfoText: TextView
    
    // UI组件 - 定时重启
    private lateinit var scheduledRestartSwitch: SwitchCompat
    private lateinit var restartTimeText: TextView
    private lateinit var setTimeButton: Button
    
    // UI组件 - 数据库备份
    private lateinit var backupDatabaseButton: Button
    private lateinit var restoreDatabaseButton: Button
    private lateinit var backupStatusText: TextView


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_program_management, container, false)
    }
    
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        
        initViews(view)
        setupClickListeners()
        observeViewModel()
    }
    
    private fun initViews(view: View) {
        // 数据管理
        clearDataButton = view.findViewById(R.id.clearDataButton)
        restartAppButton = view.findViewById(R.id.restartAppButton)
        exitAppButton = view.findViewById(R.id.exitAppButton)
        
        // 系统监控
        monitorStatusText = view.findViewById(R.id.monitorStatusText)
        startMonitorButton = view.findViewById(R.id.startMonitorButton)
        stopMonitorButton = view.findViewById(R.id.stopMonitorButton)
        memoryInfoText = view.findViewById(R.id.memoryInfoText)
        cpuInfoText = view.findViewById(R.id.cpuInfoText)
        processInfoText = view.findViewById(R.id.processInfoText)
        
        // 定时重启
        scheduledRestartSwitch = view.findViewById(R.id.scheduledRestartSwitch)
        restartTimeText = view.findViewById(R.id.restartTimeText)
        setTimeButton = view.findViewById(R.id.setTimeButton)
        
        // 数据库备份
        backupDatabaseButton = view.findViewById(R.id.backupDatabaseButton)
        restoreDatabaseButton = view.findViewById(R.id.restoreDatabaseButton)
        backupStatusText = view.findViewById(R.id.backupStatusText)
    }
    
    private fun setupClickListeners() {
        // 清空应用数据
        clearDataButton.setOnClickListener {
            showConfirmDialog(
                "清空应用数据",
                "此操作将删除所有本地数据，包括配置和记录。此操作不可恢复！\n\n确定要继续吗？"
            ) {
                clearAppData()
            }
        }
        
        // 重启程序
        restartAppButton.setOnClickListener {
            showConfirmDialog(
                "重启程序",
                "确定要重启应用程序吗？所有未保存的数据将丢失。"
            ) {
                restartApp()
            }
        }
        
        // 退出程序
        exitAppButton.setOnClickListener {
            showConfirmDialog(
                "退出程序",
                "确定要退出应用程序吗？"
            ) {
                exitApp()
            }
        }
        
        // 启动监控
        startMonitorButton.setOnClickListener {
            viewModel.startMonitoring()
            
            // 记录启动监控日志
            requireContext().logConfigChange(
                scope = viewLifecycleOwner.lifecycleScope,
                subType = "SYSTEM_MONITOR",
                description = "启动系统监控",
                oldValue = "监控停止",
                newValue = "监控运行中"
            )
        }
        
        // 停止监控
        stopMonitorButton.setOnClickListener {
            viewModel.stopMonitoring()
            
            // 记录停止监控日志
            requireContext().logConfigChange(
                scope = viewLifecycleOwner.lifecycleScope,
                subType = "SYSTEM_MONITOR",
                description = "停止系统监控",
                oldValue = "监控运行中",
                newValue = "监控停止"
            )
        }
        
        // 定时重启开关
        setupScheduledRestartSwitchListener()
        
        // 设置时间
        setTimeButton.setOnClickListener {
            showTimePicker()
        }
        
        // 备份数据库
        backupDatabaseButton.setOnClickListener {
            viewModel.backupDatabase { success, message ->
                activity?.runOnUiThread {
                    if (success) {
                        Toast.makeText(context, "备份成功", Toast.LENGTH_SHORT).show()
                        
                        // 记录备份成功日志
                        requireContext().logConfigChange(
                            scope = viewLifecycleOwner.lifecycleScope,
                            subType = "DATABASE_BACKUP",
                            description = "备份数据库成功",
                            oldValue = "",
                            newValue = "备份完成"
                        )
                    } else {
                        Toast.makeText(context, "备份失败: $message", Toast.LENGTH_LONG).show()
                        
                        // 记录备份失败日志
                        requireContext().logConfigChange(
                            scope = viewLifecycleOwner.lifecycleScope,
                            subType = "DATABASE_BACKUP",
                            description = "备份数据库失败",
                            oldValue = "",
                            newValue = "失败原因: $message"
                        )
                    }
                }
            }
        }
        
        // 恢复数据库
        restoreDatabaseButton.setOnClickListener {
            showBackupFilesDialog()
        }
    }
    
    private fun observeViewModel() {
        // 监控状态
        viewModel.monitorStatus.observe(viewLifecycleOwner) { status ->
            monitorStatusText.text = status
        }
        
        // 监控运行状态
        viewModel.isMonitoring.observe(viewLifecycleOwner) { isMonitoring ->
            startMonitorButton.isEnabled = !isMonitoring
            stopMonitorButton.isEnabled = isMonitoring
        }
        
        // 内存信息
        viewModel.memoryInfo.observe(viewLifecycleOwner) { info ->
            memoryInfoText.text = info
        }
        
        // CPU信息
        viewModel.cpuInfo.observe(viewLifecycleOwner) { info ->
            cpuInfoText.text = info
        }
        
        // 进程信息
        viewModel.processInfo.observe(viewLifecycleOwner) { info ->
            processInfoText.text = info
        }
        
        // 定时重启设置
        viewModel.scheduledRestartEnabled.observe(viewLifecycleOwner) { enabled ->
            if (scheduledRestartSwitch.isChecked != enabled) {
                // 临时移除监听器，避免触发 OnCheckedChangeListener
                scheduledRestartSwitch.setOnCheckedChangeListener(null)
                scheduledRestartSwitch.isChecked = enabled
                // 恢复监听器
                setupScheduledRestartSwitchListener()
            }
        }
        
        viewModel.restartTime.observe(viewLifecycleOwner) { time ->
            restartTimeText.text = time
        }
        
        // 备份状态
        viewModel.backupStatus.observe(viewLifecycleOwner) { status ->
            backupStatusText.text = status
        }
    }
    
    /**
     * 设置定时重启开关监听器
     */
    private fun setupScheduledRestartSwitchListener() {
        scheduledRestartSwitch.setOnCheckedChangeListener { _, isChecked ->
            // 从 TextView获取当前显示的时间（可能是用户刚设置的新时间）
            val time = restartTimeText.text.toString().ifEmpty { "01:00" }
            viewModel.saveScheduledRestartSettings(isChecked, time)
            
            if (isChecked) {
                Toast.makeText(context, "定时重启已启用，将在 $time 重启", Toast.LENGTH_SHORT).show()
                
                // 记录启用定时重启日志
                requireContext().logConfigChange(
                    scope = viewLifecycleOwner.lifecycleScope,
                    subType = "SCHEDULED_RESTART",
                    description = "启用定时重启",
                    oldValue = "禁用",
                    newValue = "启用 - 重启时间: $time"
                )
            } else {
                Toast.makeText(context, "定时重启已禁用", Toast.LENGTH_SHORT).show()
                
                // 记录禁用定时重启日志
                requireContext().logConfigChange(
                    scope = viewLifecycleOwner.lifecycleScope,
                    subType = "SCHEDULED_RESTART",
                    description = "禁用定时重启",
                    oldValue = "启用 - 重启时间: $time",
                    newValue = "禁用"
                )
            }
        }
    }
    
    /**
     * 显示确认对话框
     */
    private fun showConfirmDialog(title: String, message: String, onConfirm: () -> Unit) {
        AlertDialog.Builder(requireContext())
            .setTitle(title)
            .setMessage(message)
            .setPositiveButton("确定") { _, _ ->
                onConfirm()
            }
            .setNegativeButton("取消", null)
            .show()
    }
    /**
     * 重置初始化状态（用于测试或重新初始化）
     *
     * 警告：这将删除整个数据库！
     */
    @SuppressLint("LongLogTag")
    suspend fun resetInitialization(context: Context) {
        withContext(Dispatchers.IO) {
            try {
                Log.i(TAG, "开始重置数据库...")
                
                // 1. 先获取数据库实例并关闭
                try {
                    val db = AppDatabase.getDatabase(context)
                    db.close()
                    Log.i(TAG, "数据库连接已关闭")
                } catch (e: Exception) {
                    Log.w(TAG, "关闭数据库连接时出错: ${e.message}")
                }
                
                // 2. 清除数据库实例
                AppDatabase.clearInstance()
                
                // 3. 等待文件系统释放文件句柄
                delay(500)

                // 4. 删除数据库文件（注意：数据库名称是 "app_database"，不带 .db 后缀）
                val deleted = context.deleteDatabase("app_database")
                Log.i(TAG, "删除数据库文件结果: $deleted")
                
                // 5. 手动删除相关文件（作为备份方案）
                val dbFile = context.getDatabasePath("app_database")
                val shmFile = context.getDatabasePath("app_database-shm")
                val walFile = context.getDatabasePath("app_database-wal")
                
                if (dbFile.exists()) {
                    val dbDeleted = dbFile.delete()
                    Log.i(TAG, "手动删除数据库文件: $dbDeleted (${dbFile.absolutePath})")
                }
                if (shmFile.exists()) {
                    shmFile.delete()
                    Log.i(TAG, "删除 SHM 文件")
                }
                if (walFile.exists()) {
                    walFile.delete()
                    Log.i(TAG, "删除 WAL 文件")
                }

                Log.i(TAG, "✅ 数据库已完全删除，下次启动将重新初始化")
            } catch (e: Exception) {
                Log.e(TAG, "❌ 重置初始化状态失败: ${e.message}", e)
                throw e
            }
        }
    }
    /**
     * 清空应用数据
     * 
     * 方式1：使用 AppInitializer（推荐）- 只重置数据库
     * 方式2：删除所有应用数据（当前实现）- 完全清空
     */
    private fun clearAppData() {
        viewLifecycleOwner.lifecycleScope.launch {
            try {
                // 记录操作日志（在清空前）
                requireContext().logConfigChange(
                    scope = viewLifecycleOwner.lifecycleScope,
                    subType = "CLEAR_DATA",
                    description = "清空应用数据",
                    oldValue = "应用数据存在",
                    newValue = "所有数据已清空"
                )
                
                // 等待日志写入
                delay(500)
                
                // 方式1：只重置数据库（推荐，更快更安全）
               resetInitialization(requireContext())
                
                // 方式2：完全清空所有数据（可选，更彻底）
                // clearAllAppData()
                
                // 显示提示
                withContext(Dispatchers.Main) {
                    Toast.makeText(context, "数据库已重置，应用将重启", Toast.LENGTH_SHORT).show()
                }
                
                // 延迟后重启
                delay(1000)
                
                // 重启应用
                withContext(Dispatchers.Main) {
                    restartApp()
                }
                
            } catch (e: Exception) {
                e.printStackTrace()
                withContext(Dispatchers.Main) {
                    Toast.makeText(context, "清空数据失败: ${e.message}", Toast.LENGTH_LONG).show()
                }
                
                // 记录失败日志
                requireContext().logConfigChange(
                    scope = viewLifecycleOwner.lifecycleScope,
                    subType = "CLEAR_DATA",
                    description = "清空应用数据失败",
                    oldValue = "应用数据存在",
                    newValue = "清空失败: ${e.message}"
                )
            }
        }
    }
    
    /**
     * 完全清空所有应用数据（备用方法）
     */
    private suspend fun clearAllAppData() {
        withContext(Dispatchers.IO) {
            val cacheDir = requireContext().cacheDir
            val appDir = cacheDir.parent
            
            if (appDir != null) {
                val dir = File(appDir)
                if (dir.isDirectory) {
                    val children = dir.list()
                    children?.forEach { child ->
                        // 不删除lib目录
                        if (child != "lib") {
                            deleteDir(File(dir, child))
                        }
                    }
                }
            }
        }
    }
    
    /**
     * 删除目录
     */
    private fun deleteDir(dir: File): Boolean {
        if (dir.isDirectory) {
            val children = dir.list()
            children?.forEach { child ->
                val success = deleteDir(File(dir, child))
                if (!success) {
                    return false
                }
            }
        }
        return dir.delete()
    }
    
    /**
     * 重启应用
     */
    private fun restartApp() {
        viewLifecycleOwner.lifecycleScope.launch {
            try {
                // 同步记录日志（等待写入完成）
                withContext(Dispatchers.IO) {
                    requireContext().logConfigChange(
                        scope = viewLifecycleOwner.lifecycleScope,
                        subType = "APP_RESTART",
                        description = "重启应用程序",
                        oldValue = "运行中",
                        newValue = "正在重启"
                    )
                    // 等待日志写入完成
                    delay(500)
                }
                
                // 回到主线程执行重启
                withContext(Dispatchers.Main) {
                    val intent = requireContext().packageManager
                        .getLaunchIntentForPackage(requireContext().packageName)
                    intent?.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                    intent?.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    startActivity(intent)
                    exitProcess(0)
                }
            } catch (e: Exception) {
                e.printStackTrace()
                withContext(Dispatchers.Main) {
                    Toast.makeText(context, "重启失败: ${e.message}", Toast.LENGTH_LONG).show()
                }
            }
        }
    }
    
    /**
     * 退出应用
     */
    private fun exitApp() {
        viewLifecycleOwner.lifecycleScope.launch {
            try {
                // 同步记录日志（等待写入完成）
                withContext(Dispatchers.IO) {
                    requireContext().logConfigChange(
                        scope = viewLifecycleOwner.lifecycleScope,
                        subType = "APP_EXIT",
                        description = "退出应用程序",
                        oldValue = "运行中",
                        newValue = "已退出"
                    )
                    // 等待日志写入完成
                    delay(500)
                }
                
                // 回到主线程执行退出
                withContext(Dispatchers.Main) {
                    activity?.finish()
                    exitProcess(0)
                }
            } catch (e: Exception) {
                // 即使日志失败，也要退出
                withContext(Dispatchers.Main) {
                    activity?.finish()
                    exitProcess(0)
                }
            }
        }
    }
    
    /**
     * 显示时间选择器
     */
    private fun showTimePicker() {
        val currentTime = restartTimeText.text.toString().split(":")
        val hour = currentTime.getOrNull(0)?.toIntOrNull() ?: 1
        val minute = currentTime.getOrNull(1)?.toIntOrNull() ?: 0
        
        TimePickerDialog(
            requireContext(),
            { _, selectedHour, selectedMinute ->
                val time = String.format("%02d:%02d", selectedHour, selectedMinute)
                
                // 保存新时间到数据库（保持当前开关状态）
                // TextView会通过LiveData自动更新，不需要手动设置
                val isEnabled = scheduledRestartSwitch.isChecked
                viewModel.saveScheduledRestartSettings(isEnabled, time)
                
                if (isEnabled) {
                    Toast.makeText(context, "定时重启时间已更新为 $time", Toast.LENGTH_SHORT).show()
                } else {
                    Toast.makeText(context, "重启时间已设置为 $time", Toast.LENGTH_SHORT).show()
                }
                
                // 记录设置重启时间日志
                val oldTime = currentTime.joinToString(":")
                requireContext().logConfigChange(
                    scope = viewLifecycleOwner.lifecycleScope,
                    subType = "SCHEDULED_RESTART",
                    description = "修改定时重启时间",
                    oldValue = "重启时间: $oldTime",
                    newValue = "重启时间: $time${if (isEnabled) " (已启用)" else " (未启用)"}"
                )
            },
            hour,
            minute,
            true
        ).show()
    }
    
    /**
     * 显示备份文件列表对话框
     */
    private fun showBackupFilesDialog() {
        val backupFiles = viewModel.listBackupFiles()
        
        if (backupFiles.isEmpty()) {
            Toast.makeText(context, "没有找到备份文件", Toast.LENGTH_SHORT).show()
            return
        }
        
        val fileNames = backupFiles.map { file ->
            val date = java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault())
                .format(java.util.Date(file.lastModified()))
            "${file.name}\n最后修改: $date"
        }.toTypedArray()
        
        AlertDialog.Builder(requireContext())
            .setTitle("选择备份文件")
            .setItems(fileNames) { _, which ->
                val selectedFile = backupFiles[which]
                showConfirmDialog(
                    "恢复数据库",
                    "确定要从备份恢复数据库吗？\n\n当前数据将被覆盖！\n\n备份文件: ${selectedFile.name}"
                ) {
                    viewModel.restoreDatabase(selectedFile.absolutePath) { success, message ->
                        activity?.runOnUiThread {
                            if (success) {
                                Toast.makeText(context, "恢复成功，应用将重启", Toast.LENGTH_SHORT).show()
                                
                                // 记录恢复成功日志
                                requireContext().logConfigChange(
                                    scope = viewLifecycleOwner.lifecycleScope,
                                    subType = "DATABASE_RESTORE",
                                    description = "恢复数据库成功",
                                    oldValue = "当前数据库",
                                    newValue = "从备份恢复: ${selectedFile.name}"
                                )
                                
                                android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
                                    restartApp()
                                }, 1000)
                            } else {
                                Toast.makeText(context, "恢复失败: $message", Toast.LENGTH_LONG).show()
                                
                                // 记录恢复失败日志
                                requireContext().logConfigChange(
                                    scope = viewLifecycleOwner.lifecycleScope,
                                    subType = "DATABASE_RESTORE",
                                    description = "恢复数据库失败",
                                    oldValue = "",
                                    newValue = "失败原因: $message"
                                )
                            }
                        }
                    }
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    override fun onDestroyView() {
        super.onDestroyView()
        viewModel.stopMonitoring()
    }
}